const Koa = require("koa");
const router = require("koa-router")();
const static = require("koa-static");
const render = require("koa-art-template");
const path = require("path");
const bodyParser = require("koa-bodyparser");
const session = require("koa-session");
const sd = require("silly-datetime");
const jsonp = require("koa-jsonp");
const cors = require("koa2-cors");
let app = new Koa();

/* 引入模块 */
let admin = require("./routes/admin");
let api = require("./routes/api");
let defaul = require("./routes/default");
/* 配置art-template模板引擎 */
render(app, {
  root: path.join(__dirname, "views"),
  extname: ".html",
  debug: process.env.NODE_ENV !== "production",
  dateFormat: (dateFormat = function (value) {
    /*扩展模板里面的方法*/
    return sd.format(value, "YYYY-MM-DD HH:mm");
  }),
});

/* 配置koa-session的中间件配置 */
app.keys = ["some secret hurr"]; //cookie的签名，没什么用
const CONFIG = {
  key: "koa:sess",
  maxAge: 86400000,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: false,
  renew: true,
};

app.use(
  cors({
    origin: function (ctx) {
      return "http://localhost:8080";
    },
  })
);

app.use(session(CONFIG, app));

/* 配置静态资源服务 */
app.use(static(__dirname + "/public"));

/* 使用body-parser中间件 */
app.use(bodyParser());

/* 使用koa-jsonp */
app.use(jsonp());
router.use("/admin", admin);
router.use("/api", api);
router.use("/", defaul);

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000, () => {
  console.log("the server is running at http://localhost:3000");
});
